package com.jbinfo.qingcaowan.exam.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.bana.common.util.page.PageCond;
import org.bana.common.util.page.PageCondUtil;
import org.springframework.stereotype.Service;

import com.jbinfo.common.utils.DataTables;
import com.jbinfo.qingcaowan.common.BusinessException;
import com.jbinfo.qingcaowan.common.ClonePojoUtil;
import com.jbinfo.qingcaowan.common.JSONResult;
import com.jbinfo.qingcaowan.common.ExceptionConstants.BusinessExceptionCode;
import com.jbinfo.qingcaowan.exam.dao.ChooseAnswerDao;
import com.jbinfo.qingcaowan.exam.dao.CircleDao;
import com.jbinfo.qingcaowan.exam.dao.ExamScoreDao;
import com.jbinfo.qingcaowan.exam.dao.ExamUserDao;
import com.jbinfo.qingcaowan.exam.dao.QuestionDao;
import com.jbinfo.qingcaowan.exam.dto.ExamCircleDTO;
import com.jbinfo.qingcaowan.exam.dto.ExamScoreDTO;
import com.jbinfo.qingcaowan.exam.entity.CircleSearchModel;
import com.jbinfo.qingcaowan.exam.entity.ExamChooseAnswer;
import com.jbinfo.qingcaowan.exam.entity.ExamCircle;
import com.jbinfo.qingcaowan.exam.entity.ExamQuestion;
import com.jbinfo.qingcaowan.exam.service.CircleService;
import com.jbinfo.qingcaowan.exam.service.ExamScoreService;
import com.jbinfo.qingcaowan.user.service.OrgService;
import com.jbinfo.common.utils.DataCommUtil;

@Service("circleService")
public class CircleServiceImpl implements CircleService {
	
	@Resource(name="circleDao")
	private CircleDao circleDao;
	@Resource(name="questionDao")
	private QuestionDao questionDao;
	@Resource(name="chooseAnswerDao")
	private ChooseAnswerDao chooseAnswerDao;
	@Resource
	private OrgService orgService;
	
	@Resource(name="examUserDao")
	private ExamUserDao examUserDao;
	
	@Resource(name="examScoreDao")
	private ExamScoreDao examScoreDao;
	
	@Resource
	private ExamScoreService examScoreService;
	
	@Override
	public List<ExamCircle> list(CircleSearchModel model) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void add(ExamCircle examCircle) {
		String examCircleId = UUID.randomUUID().toString();//声明试卷id
		String questionId = null;//声明试卷id
		//保存试卷主表
		examCircle.setId(examCircleId);
		circleDao.insert(examCircle);
		//获取表单的问题list
		List<ExamQuestion> questionList = examCircle.getQuestionList();
		//表单答案list
		List<ExamChooseAnswer> chooseAnswerList;
		if(questionList != null && questionList.size()>0){
			for(ExamQuestion question : questionList){
				if(question != null){
					//将试卷的id绑定到问题数据中
					question.setExamCircle(examCircleId);
					questionId = UUID.randomUUID().toString();
					question.setId(questionId);
					//保存问题数据 
					questionDao.insert(question);
					//获取表单答案list
					chooseAnswerList = question.getChooseAnswerList();
					if(chooseAnswerList != null && chooseAnswerList.size()>0){
						for(ExamChooseAnswer chooseAnswer : chooseAnswerList){
							if(chooseAnswer != null){
								chooseAnswer.setId(UUID.randomUUID().toString());
								//将问题id绑定到答案中
								chooseAnswer.setQuestionId(questionId);
								//保存答案
								chooseAnswerDao.insert(chooseAnswer);
							}
						}
					}
				}
			}
		}
	} 

	@Override
	public void update(ExamCircle examCrile) {
		// TODO Auto-generated method stub

	}

	@Override
	public void delete(String id) {
		// TODO Auto-generated method stub

	}

	@Override
	public ExamCircle searchById(String id) {
		// TODO Auto-generated method stub
		return (ExamCircle) circleDao.selectByPrimaryKey(id);
	}
	
	@Override
	public DataTables<ExamCircle> findByParam(CircleSearchModel circleSearchModel) {
		List<ExamCircle> tList = circleDao.findByParam(circleSearchModel);
		return DataTables.combinTotalRecords(tList);
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<ExamCircle> listAll(CircleSearchModel model) {
		model = new CircleSearchModel();
		return (List<ExamCircle>) circleDao.selectForList("selectAll", model);
	}

	// 查询未考试的试卷列表
	@Override
	public Object findNoExamCircleList(ExamCircleDTO examCircleDTO) {

		List<ExamCircleDTO> dtoList = new ArrayList<ExamCircleDTO>();
		
		// 根据orgId 查询所有parentOrgId
		JSONResult pOrgJson = (JSONResult) orgService.getParentOrgId(examCircleDTO.getOrgId());
		String pOrgId = pOrgJson.getResultBean();
		
		String [] orgIds = pOrgId.split(",");
		
		List<String> orgIdList = new ArrayList<String>();
		
		for (int i = 0; i < orgIds.length; i++) {
			String orgId = orgIds[i];
			orgIdList.add(orgId);
		}
		orgIdList.add(examCircleDTO.getOrgId());
		// 去重
		DataCommUtil.removeDup(orgIdList);
		
		Date queryDate = examCircleDTO.getQueryDate();
		
		List<ExamCircle> circleList = circleDao.selectExamCircleList(orgIdList, queryDate);
		
		if (circleList != null && !circleList.isEmpty()) {
			for (ExamCircle examCircle : circleList) {
				ExamCircleDTO dto = ClonePojoUtil.copyClassFromTo(examCircle, ExamCircleDTO.class);
				// 处理考试开始时间、结束时间
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String strBeginTime = sdf.format(dto.getBeginTime());
				String strEndTime = sdf.format(dto.getEndTime());
				dto.setStrBeginTime(strBeginTime);
				dto.setStrEndTime(strEndTime);
				
				// 答题状态
				ExamScoreDTO queryDTO = new ExamScoreDTO();
				queryDTO.setUserId(examCircleDTO.getUserId());
				queryDTO.setExamCode(examCircle.getExamCode());
				PageCond pageCond = null;
				PageCond pageCondQuery = PageCondUtil.check(pageCond);
				
				List<ExamScoreDTO> examScoreList = examScoreDao.findUserExamScore(queryDTO, pageCondQuery);
				
						// 考试答题状态
				String examUserStatus = "0";
				// 判断非空
				if (examScoreList != null && !examScoreList.isEmpty()) {
					examUserStatus = "1";
				}
				dto.setExamUserStatus(examUserStatus);
				
				dtoList.add(dto);
			}
		}
		return dtoList;
	}

	// 查询已参加考试的人数
	@Override
	public Object findTotalExamNum(ExamCircleDTO examCircleDTO) {
		if (examCircleDTO.getExamCode() == null
				|| examCircleDTO.getExamCode().isEmpty()) {
			throw new BusinessException(BusinessExceptionCode.param_error, "考试编码不能为空!");
		}
		if (examCircleDTO.getUserId() == null
				|| examCircleDTO.getUserId().isEmpty()) {
			throw new BusinessException(BusinessExceptionCode.param_error, "用户编码不能为空!");
		}
		
		/*ExamUserDTO examUserDTO = new ExamUserDTO();
		examUserDTO.setUserId(examCircleDTO.getUserId());
		
		List<ExamUserDomain> domainList = examUserDao.findExamUser(examUserDTO);
		
		// 考试答题状态
		String examUserStatus = "0";
		// 判断非空
		if (domainList != null && !domainList.isEmpty()) {
			examUserStatus = "1";
		}*/
		
		ExamCircleDTO dto = new ExamCircleDTO();
		Integer nCurExamNum = circleDao.findCurExamNum(examCircleDTO);
		dto.setExamUserNum(nCurExamNum);
//		dto.setExamUserStatus(examUserStatus);
		// 保存考试分数
		ExamCircleDTO examCircle = new ExamCircleDTO();
		examCircle.setUserId(examCircleDTO.getUserId());
		examCircle.setExamCircle(examCircleDTO.getExamCode());
		dto = (ExamCircleDTO) examScoreService.findExamScore(examCircleDTO);
		
		return dto;
	}

}
